package fastwave.cloud.demo.fastwave.biz.publisher.service;

import com.alibaba.fastjson.JSON;
import fastwave.cloud.demo.fastwave.biz.publisher.config.TransConfig;
import fastwave.cloud.demo.fastwave.biz.publisher.domain.MsgLog;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.dc.pr.PRError;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * <p>Title: TransTransferService</p>
 *
 * @author: dwLiu
 * @date: 2020/4/11 22:25
 */
@Service
public class TransferMQService {

    @Resource(name = "TemplateTrans")
    RabbitTemplate rabbitTemplate;

    @Autowired
    MsgLogService msgLogService;

    @PostConstruct
    private void initRabbitTemplete(){
        //设置消息发送确认回调，发送成功后更新消息表状态
        rabbitTemplate.setConfirmCallback((CorrelationData correlationData, boolean ack, String cause)->{
               if(ack){
                   MsgLog msgLog = new MsgLog();
                   msgLog.setMsgId(correlationData.getId());
                   msgLog.setStatus(1);
                   msgLogService.updateById(msgLog);
               }
        });
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                MsgLog msgLog = new MsgLog();
                Date curTime = new Date();
                msgLog.setMsgId(UUID.randomUUID().toString());
                msgLog.setMsg(message.toString());
                msgLog.setExchange(exchange);
                msgLog.setRoutingKey(routingKey);
                msgLog.setCreateTime(curTime);
                msgLog.setUpdateTime(curTime);
                msgLog.setNextTryTime(curTime);
                msgLog.setStatus(4);
                msgLogService.save(msgLog);
            }
        });

    }


    public void sendMessage(Map<String, Object> param) {
        String msg = JSON.toJSONString(param);
        String transId = param.get("transId").toString();
        Message message = MessageBuilder.withBody(msg.getBytes())
                .setMessageId(transId)
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                .build();
        rabbitTemplate.convertAndSend(TransConfig.TRANSFER_EXCHANGE_NAME,
                TransConfig.TRANSFER_ROUTING_KEY,msg,new CorrelationData(transId));

    }
}
